package org.luxor.commons.schedule.config;

import org.luxor.commons.core.utils.AssertUtils;
import org.luxor.commons.jdbc.config.DynamicDataSourceConfig;
import org.luxor.commons.jdbc.plugin.dynamic.provider.DynamicDataSourceProvider;
import org.luxor.commons.schedule.config.properties.QuartzExtendProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.quartz.QuartzDataSource;
import org.springframework.boot.autoconfigure.quartz.QuartzProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.Map;

/**
 * 任务调度器数据源配置
 *
 * @author Mr.yan @date 2020/3/3
 */
@Configuration
@AutoConfigureAfter(DynamicDataSourceConfig.class)
@ConditionalOnClass(DynamicDataSourceConfig.class)
@EnableConfigurationProperties({QuartzProperties.class, QuartzExtendProperties.class})
@ConditionalOnProperty(prefix = "spring.quartz", name = "job-store-type", havingValue = "jdbc")
public class QuartzJdbcConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(QuartzJdbcConfiguration.class);


    @Bean("quartzDataSource")
    @QuartzDataSource
    @ConditionalOnClass(DynamicDataSourceProvider.class)
    public DataSource quartzDataSource(QuartzExtendProperties quartzExtendProperties,
                                       ObjectProvider<DynamicDataSourceProvider> dynamicDataSourceProvider) {
        logger.info("Quartz DataSource is set to [{}], Started...", quartzExtendProperties.getDataSource());

        try {
            Map<String, DataSource> dataSources = dynamicDataSourceProvider.getIfUnique().loadDataSources();
            DataSource quartzDataSource = dataSources.get(quartzExtendProperties.getDataSource());

            AssertUtils.notNull(quartzDataSource, "There's no [" + quartzExtendProperties.getDataSource() + "] in DynamicDataSources");

            logger.info("Quartz DataSource is set to [{}], completed.", quartzExtendProperties.getDataSource());
            return quartzDataSource;
        } catch (Exception e) {
            logger.error("Quartz DataSource is set to  [{}], Failure.", quartzExtendProperties.getDataSource(), e);
            throw e;
        }
    }

}
